var xhr;

/*****************************************************************************/
function updateProduct(name, number) {
    qty = document.getElementById(number + 'qty').value;
    if (qty <= 0) {
        deleteProduct(name, number);
    }
    else {
        var products = getCookie('products');
        var i = products.indexOf(name);
        var p = products.substring(i);
        for (u = 0; u < 2; u ++) {
            i = i + p.indexOf(':');
            p = products.substring(i+1);
        }
        p = products.substring(i+2);
        var j = p.indexOf(':') + 1;
        p = p.substring(j);
        j = products.indexOf(p);

        document.cookie = 'products=' + products.substring(0, i+2) + qty + ":" + products.substring(j);
        products = products.substring(0, i+2) + qty + ":" + products.substring(j);
        products = products.split('/');
        document.getElementById("totalprice").innerHTML = "$" + calculateTotalPrice(products);

        var productdata = products[number].split(':');
        document.getElementById("extended" + number).innerHTML = "$" + (productdata[3] * productdata[2]);
        
        displayPopup("Item Updated!", "center", 2000);
    }
}
/*****************************************************************************/
function deleteProduct(name, number) {
    var products = getCookie('products');
    var i = products.indexOf(name);
    var secondHalf = products.substring(i);
    var nextIndex = secondHalf.indexOf('/');
    if (nextIndex == -1) {
        secondHalf = '';
    }
    else {
        secondHalf = secondHalf.substring(nextIndex+1);
    }
    document.cookie = 'products=' + products.substring(0, i-1) + secondHalf;

    products = products.substring(0, i-1) + secondHalf;
    products = products.split('/');
    if (products != "") {
        document.getElementById(number).innerHTML = "";
        document.getElementById("totalprice").innerHTML = "$" + calculateTotalPrice(products);
        displayPopup("Item Deleted!", "center", 2000);
    }
    else {
        document.getElementById("form1").innerHTML = "There are no items in your shopping cart!";
    }
}
/*****************************************************************************/
function calculateTotalPrice(products) {
    var totalprice = 0;

    for (var i = 0; i < products.length; i ++) {
        var productdata = products[i].split(':');
        totalprice += (parseInt(productdata[3]) * parseInt(productdata[2]));
    }

    return totalprice;
}
/*****************************************************************************/
function getSuggestions() {
    
    if (window.ActiveXObject) {
        xhr = new ActiveXObject("Microsoft.XMLHTTP");
    }
    else if(window.XMLHttpRequest){
        xhr = new XMLHttpRequest;
    }

    //build query string
    var strQuery = "strType=suggest&customerID=" + getCookie('CustomerID');
    var cookie = getCookie('products');
    cookie = cookie.split('/');
    var products = new Array(cookie.length);
    for (var i = 0; i < cookie.length; i ++) {
        var productdata = cookie[i].split(':');
        products[i] = productdata[0];
    }
    strQuery = strQuery + "&products=" + products;

    //setup xhr

    xhr.open("POST", "ShoppingCartServlet1?timeStamp=" + new Date().getTime(), true);
    xhr.onreadystatechange = handleSuggestionsResponse;
    xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

    xhr.send(strQuery);
}
/*****************************************************************************/
function handleSuggestionsResponse() {
    
    if (xhr.readyState != 4) return;
    if (xhr.status != 200) return;
    
    //handle the response

    var xhresponse = xhr.responseXML;
    var nodError = xhresponse.getElementsByTagName("ErrorCode")[0].firstChild.nodeValue;

    if (nodError != 0) {
        hidePopup(document.getElementById('divPopup'));
        displayPopup("We are currently experiencing problems on our system. Please try again later.", "center", 2000);
        document.getElementById("placeOrder").style.display = "none";
    }
    else {
        var products = xhresponse.getElementsByTagName('Product');
        var productIDs = xhresponse.getElementsByTagName('ProductID');
        var productNames = xhresponse.getElementsByTagName('ProductName');
        var productImages = xhresponse.getElementsByTagName('ProductImage');
        var productPrices = xhresponse.getElementsByTagName('ProductPrice');
        document.getElementById('tableSuggestions').innerHTML = "";
        for(var i=0; i<products.length; i++){
            document.getElementById('tableSuggestions').innerHTML += "<tr><td width=\"97\">" + productNames[i].firstChild.nodeValue + "</td><td width=\"121\" rowspan=\"2\"><img src=\"" + productImages[i].firstChild.nodeValue + "\" width=\"118\" height=\"88\" />" +
            "</td><td width=\"92\" rowspan=\"2\"><a href=\"javascript:addToCart(" + productIDs[i].firstChild.nodeValue + "," + productNames[i].firstChild.nodeValue + "," + productPrices[i].firstChild.nodeValue + ")\">Add To Cart </a></td></tr><tr>" +
            "<td><div align=\"right\">$" + productPrices[i].firstChild.nodeValue + "</div></td></tr>";;
        }
        if (products.length == 0) {
            hideDiv(document.getElementById('divSuggestions'));
        }
    }
}
/*****************************************************************************/
function checkout() {
    if (checkLogin()) {
        window.location = ("billing.html");
    }
    else {
        document.getElementById("divError").style.display = "block";
        document.getElementById("divError").innerHTML = "You have to be logged in to checkout! Please login <a href=\"login.html\">here</a>. :)";
    }
}
/*****************************************************************************/
function fillBillingAndShippingInfo() {
    
    if (window.ActiveXObject) {
        xhr = new ActiveXObject("Microsoft.XMLHTTP");
    }
    else if(window.XMLHttpRequest){
        xhr = new XMLHttpRequest;
    }
    
    //build query string
    var strQuery = "strType=fill&customerID=" + getCookie('CustomerID');

    //setup xhr
    
    xhr.open("POST", "ShoppingCartServlet1?timeStamp=" + new Date().getTime(), true);
    xhr.onreadystatechange = handleFillBillingAndShippingResponse;
    xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

    xhr.send(strQuery);
    displayPopup("Please hold while we retrieve your information.", "center", 999999999);
}
/*****************************************************************************/
function handleFillBillingAndShippingResponse(){
    if (xhr.readyState != 4) return;
    if (xhr.status != 200) return;

    //handle the response
    var xhresponse = xhr.responseXML;
    
    var nodError = xhresponse.getElementsByTagName("ErrorCode")[0].firstChild.nodeValue;

    if (nodError != 0) {
        hidePopup(document.getElementById('divPopup'));
        displayPopup("We are currently experiencing problems on our system. Please try again later.", "center", 2000);
        document.getElementById("placeOrder").style.display = "none";
    }
    else {
        document.getElementById("txtFirstName").value = getCookie("FirstName");
        document.getElementById("txtLastName").value = xhresponse.getElementsByTagName("LastName")[0].firstChild.nodeValue;
        document.getElementById("txtEmail").value = xhresponse.getElementsByTagName("Email")[0].firstChild.nodeValue;
        document.getElementById("txtCreditCardNumber").value = xhresponse.getElementsByTagName("CCNo")[0].firstChild.nodeValue.substring(0, 4) + "************";
        document.getElementById("selCreditCardType").value = xhresponse.getElementsByTagName("CardType")[0].firstChild.nodeValue;
        document.getElementById("txtCreditCardHolder").value = xhresponse.getElementsByTagName("CardHolder")[0].firstChild.nodeValue;
        document.getElementById("selCountry").value = xhresponse.getElementsByTagName("Country")[0].firstChild.nodeValue;
        document.getElementById("txtCity").value = xhresponse.getElementsByTagName("City")[0].firstChild.nodeValue;
        document.getElementById("txtState").value = xhresponse.getElementsByTagName("State")[0].firstChild.nodeValue;
        document.getElementById("txtAddressLine1").value = xhresponse.getElementsByTagName("AddressLine1")[0].firstChild.nodeValue;
        document.getElementById("txtAddressLine2").value = xhresponse.getElementsByTagName("AddressLine2")[0].firstChild.nodeValue;
        document.getElementById("txtPostalCode").value = xhresponse.getElementsByTagName("PostalCode")[0].firstChild.nodeValue;
        hidePopup(document.getElementById('divPopup'));
    }
}
/*****************************************************************************/
function toggleDiv(divid){
    if(document.getElementById(divid).style.display == 'none'){
        document.getElementById(divid).style.display = 'block';
        document.getElementById("mydivEdit" + divid.charAt(5)).style.display = 'inline';
    }
    else{
        document.getElementById(divid).style.display = 'none';
        document.getElementById("mydivEdit" + divid.charAt(5)).style.display = 'none';
    }
}
/*****************************************************************************/
function sameAsBilling() {
    document.getElementById("selShippingCountry").value = document.getElementById("selCountry").value;
    document.getElementById("txtShippingCity").value = document.getElementById("txtCity").value;
    document.getElementById("txtShippingState").value = document.getElementById("txtState").value;
    document.getElementById("txtShippingAddressLine1").value = document.getElementById("txtAddressLine1").value;
    document.getElementById("txtShippingAddressLine2").value = document.getElementById("txtAddressLine2").value;
    document.getElementById("txtShippingPostalCode").value =  document.getElementById("txtPostalCode").value;
}
/*****************************************************************************/
function placeOrder() {
    if (!checkFields()) {
        displayPopup("Please fill in all the fields!", "center", 2000);
        return;
    }
    var customerData;
    customerData =  document.getElementById("txtFirstName").value + "///" +
    document.getElementById("txtLastName").value + "///" +
    document.getElementById("txtEmail").value + "///";

    var creditCardNo;

    if (document.getElementById("txtCreditCardNumber").value.indexOf('*') == -1) {
        creditCardNo = document.getElementById("txtCreditCardNumber").value;
    }
    else {
        temp = getCookie('customerData');
        temp = temp.split("///");
        creditCardNo = temp[3];
       
    }
    document.getElementById("done").innerText = "";
    checkCreditCardInfo(creditCardNo, document.getElementById("selCreditCardType").value);
    customerData = customerData + creditCardNo + "///";
    
    document.getElementById("lala").innerText = customerData;
    setTimeout("recursiveWait()", 2000)
    displayPopup("Please wait", "center", 2000);
}
/*****************************************************************************/
function checkFields() {
    if (document.getElementById("txtCreditCardNumber").value == "")
        return false;
    else if (document.getElementById("selCreditCardType").value == "-1")
        return false;
    else if (document.getElementById("txtCreditCardHolder").value == "")
        return false;
    else if (document.getElementById("selCountry").value == "00")
        return false;
    else if (document.getElementById("txtCity").value == "")
        return false;
    else if (document.getElementById("txtState").value == "")
        return false;
    else if (document.getElementById("txtAddressLine1").value == "")
        return false;
    else if (document.getElementById("txtAddressLine2").value == "")
        return false;
    else if (document.getElementById("txtPostalCode").value == "")
        return false;
    else if (document.getElementById("selShippingCountry").value == "00")
        return false;
    else if (document.getElementById("txtShippingCity").value == "")
        return false;
    else if (document.getElementById("txtShippingState").value == "")
        return false;
    else if (document.getElementById("txtShippingAddressLine1").value == "")
        return false;
    else if (document.getElementById("txtShippingAddressLine2").value == "")
        return false;
    else if (document.getElementById("txtShippingPostalCode").value == "")
        return false;
    return true;
}
/*****************************************************************************/
function recursiveWait() {
    if (document.getElementById("done").innerText == ""){
        setTimeout("recursiveWait()", 2000);
        displayPopup("Please wait", "center", 2000);
    }
    else {
        placeOrder2();
    }
}
/*****************************************************************************/
function placeOrder2() {
    if (document.getElementById("creditCardCheck").innerText == "true") {
        
    }
    else {
        displayPopup("Please check that your credit card information is correct.", "center", 2000);
        return;
    }

    var customerData = document.getElementById("lala").innerText;
    customerData = customerData + document.getElementById("selCreditCardType").value + "///" +
    document.getElementById("txtCreditCardHolder").value + "///" +
    document.getElementById("txtCreditCardCVV").value + "///" +
    document.getElementById("selDeliveryDate").value + "///" +
    document.getElementById("selCountry").value + "///" +
    document.getElementById("txtCity").value + "///" +
    document.getElementById("txtState").value + "///" +
    document.getElementById("txtAddressLine1").value + "///" +
    document.getElementById("txtAddressLine2").value + "///" +
    document.getElementById("txtPostalCode").value + "///" +
    document.getElementById("selShippingCountry").value + "///" +
    document.getElementById("txtShippingCity").value + "///" +
    document.getElementById("txtShippingState").value + "///" +
    document.getElementById("txtShippingAddressLine1").value + "///" +
    document.getElementById("txtShippingAddressLine2").value + "///" +
    document.getElementById("txtShippingPostalCode").value + "///";

    document.cookie = 'customerData =' + customerData;
    window.location = ("place-order.html");
}
/*****************************************************************************/
function checkCreditCardInfo(ccno, type) {
    if (window.ActiveXObject) {
        xhr = new ActiveXObject("Microsoft.XMLHTTP");
    }
    else if(window.XMLHttpRequest){
        xhr = new XMLHttpRequest;
    }

    //build query string
    var strQuery = "strType=check&cc_num=" + ccno + "&cc_type=" + type;
    //setup xhr

    xhr.open("POST", "ShoppingCartServlet1?timeStamp=" + new Date().getTime(), true);
    xhr.onreadystatechange = handleCheckCreditCardResponse;
    xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

    xhr.send(strQuery);
}
/*****************************************************************************/
function handleCheckCreditCardResponse(){
    
    if (xhr.readyState != 4) return;
    if (xhr.status != 200) return;
    

    //handle the response
    var xhresponse = xhr.responseXML;
    var nodErrors = xhresponse.getElementsByTagName("Error");
    document.getElementById("done").innerText = "Done";
    if (nodErrors.length == 0) {
        document.getElementById("creditCardCheck").innerText = "true";
    }
    else {
        document.getElementById("creditCardCheck").innerText = "false";
    }
}
/*****************************************************************************/
function confirmOrder() {
    if (window.ActiveXObject) {
        xhr = new ActiveXObject("Microsoft.XMLHTTP");
    }
    else if(window.XMLHttpRequest){
        xhr = new XMLHttpRequest;
    }

    //build query string
    var strQuery = "strType=order&customerID=" + getCookie("CustomerID") + "&strCustomerData=" + getCookie("customerData") + "&strProducts=" + getCookie("products");

    //setup xhr

    xhr.open("POST", "ShoppingCartServlet1?timeStamp=" + new Date().getTime(), true);
    xhr.onreadystatechange = handleOrderResponse;
    xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

    xhr.send(strQuery);
}
/*****************************************************************************/
function handleOrderResponse(){

    if (xhr.readyState != 4) return;
    if (xhr.status != 200) return;

    //handle the response
    var xhresponse = xhr.responseXML;
    var nodError = xhresponse.getElementsByTagName("ErrorCode")[0].firstChild.nodeValue;
    
    if ((nodError != 0)) {
        displayPopup("We are currently experiencing problems on our system. Please try to again later.", "center", 2000);
    }
    else {
        var mydiv4 = document.getElementById("mydiv4").innerHTML;
        mydiv4 = mydiv4.substring(0, 7) + "align=\"center\" " + mydiv4.substring(7);
        document.getElementById("divMain").innerHTML = "<p>&gt;Edit Cart &gt; Billing and Shopping &gt; <u>Place Order</u></p><fieldset id=\"divInvoice\" style=\"text-align:center;width:550px;margin-left: 200px;\"></fieldset>";
        document.getElementById("divInvoice").innerHTML = "&lt;Thank You Message&gt; <br/>Order ID: " + xhresponse.getElementsByTagName("OrderID")[0].firstChild.nodeValue + " <br/>Customer ID: " + getCookie("CustomerID") +" <br/>Order Items: <br/><fieldset style=\"text-align:center;\">" + mydiv4 + "</fieldset><p style=\"text-align:center;\">*Please save the Order ID so as to assist in your tracking of your order. :) </p>";
        //deleteCookie('products');
    }
}
/*****************************************************************************/